<template>
  <div class="business-manage-container">
    <!-- 顶部导航栏 -->
    <header class="manage-header">
      <i class="fa fa-arrow-left back-btn" @click="goBack"></i>
      <h1>店铺管理</h1>
      <i class="fa fa-cog settings-btn" @click="gotoManage"></i>
    </header>

    <!-- 主要内容区域 -->
    <main class="manage-main">
      <!-- 店铺信息卡片 -->
      <div class="info-card">
        <div class="card-header">
          <i class="fa fa-store card-icon"></i>
          <h2 class="shop-name">{{ info.businessName || '—' }}</h2>
        </div>
        <div class="card-content">
          <div class="info-item">
            <i class="fa fa-map-marker-alt"></i>
            <div class="info-content">
              <span class="info-label">店铺地址</span>
              <span class="info-value">{{ info.businessAddress || '—' }}</span>
            </div>
          </div>
          <div class="info-grid">
            <div class="info-item">
              <i class="fa fa-shopping-bag"></i>
              <div class="info-content">
                <span class="info-label">起送价</span>
                <span class="info-value highlight">¥{{ fmt(info.startPrice) }}</span>
              </div>
            </div>
            <div class="info-item">
              <i class="fa fa-motorcycle"></i>
              <div class="info-content">
                <span class="info-label">配送费</span>
                <span class="info-value highlight">¥{{ fmt(info.deliveryPrice) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 营业状态设置 -->
      <div class="status-card">
        <div class="card-header">
          <i class="fa fa-clock card-icon"></i>
          <h2>营业状态</h2>
        </div>
        <div class="status-content">
          <div class="status-toggle">
            <div class="toggle-option" :class="{ active: openStatus === 'opening' }" @click="openStatus = 'opening'">
              <i class="fa fa-store"></i>
              <span>营业中</span>
              <div class="status-indicator" v-if="openStatus === 'opening'">
                <i class="fa fa-check"></i>
              </div>
            </div>
            <div class="toggle-option" :class="{ active: openStatus === 'closing' }" @click="openStatus = 'closing'">
              <i class="fa fa-door-closed"></i>
              <span>已打烊</span>
              <div class="status-indicator" v-if="openStatus === 'closing'">
                <i class="fa fa-check"></i>
              </div>
            </div>
          </div>
          <button class="save-btn" @click="saveOpenStatus" :disabled="saving">
            <i class="fa" :class="saving ? 'fa-spinner fa-spin' : 'fa-save'"></i>
            {{ saving ? '保存中...' : '保存状态' }}
          </button>
        </div>
      </div>

      <!-- 订单处理 -->
      <div class="orders-card">
        <div class="card-header">
          <i class="fa fa-list-alt card-icon"></i>
          <h2>订单处理</h2>
          <span class="orders-count">{{ orders.length }} 个订单</span>
        </div>

        <!-- 加载状态 -->
        <div v-if="loadingOrders" class="loading-state">
          <div class="loading-spinner">
            <i class="fa fa-spinner fa-spin"></i>
          </div>
          <p>订单加载中...</p>
        </div>

        <!-- 空状态 -->
        <div v-else-if="!orders.length" class="empty-state">
          <div class="empty-icon">
            <i class="fa fa-file-invoice"></i>
          </div>
          <p>暂无待处理订单</p>
          <span class="empty-tip">（不包含未支付订单）</span>
        </div>

        <!-- 订单列表 -->
        <div v-else class="orders-list">
          <div v-for="order in orders" :key="order.id" class="order-item" :data-status="order.status">
            <div class="order-header">
              <div class="order-id">
                <i class="fa fa-hashtag"></i>
                <span>#{{ order.id }}</span>
              </div>
              <div class="order-status" :class="'status-' + order.status.toLowerCase()">
                {{ orderText(order.status) }}
              </div>
            </div>

            <div class="order-content">
              <div class="order-summary">
                <i class="fa fa-clipboard-list"></i>
                <span>{{ order.summary || '—' }}</span>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="order-actions">
              <button v-if="order.status === 'PAID'" class="action-btn accept-btn"
                @click="updateOrder(order, 'received')">
                <i class="fa fa-check-circle"></i>
                接单
              </button>

              <button v-if="order.status === 'PAID'" class="action-btn reject-btn"
                @click="updateOrder(order, 'rejected')">
                <i class="fa fa-times-circle"></i>
                拒单
              </button>

              <button v-if="order.status === 'RECEIVED'" class="action-btn complete-btn"
                @click="updateOrder(order, 'ended')">
                <i class="fa fa-flag-checkered"></i>
                完成
              </button>
            </div>
          </div>
        </div>
      </div>
    </main>


  </div>
</template>

<script>
export default {
  name: 'BusinessManage',
  data() {
    return {
      id: '',
      token: '',
      info: {},
      openStatus: 'closing',
      saving: false,
      orders: [],
      loadingOrders: false
    }
  },
  mounted() {
    this.id = this.$route?.params?.id || this.$route?.query?.businessId || this.$route?.query?.id
    this.token = localStorage.getItem('token') || ''
    if (!this.id) {
      this.$nextTick(() => this.goBack())
      return
    }
    this.fetchInfo()
    this.fetchOrders()
  },
  methods: {
    gotoManage() {
      this.$router.push({ path: '/manage', query: { businessId: this.id } });
    },
    goBack() {
      this.$router.push({ path: '/mine' });
    },
    fmt(v) { return (v == null ? 0 : Number(v)).toFixed(2) },

    orderText(s) {
      const S = (s || '').toUpperCase()
      if (S === 'UNPAID') return '未支付'
      if (S === 'PAID') return '待接单'
      if (S === 'RECEIVED') return '进行中'
      if (S === 'ENDED') return '已完成'
      if (S === 'REFUNDED') return '已退款'
      if (S === 'REJECTED') return '已拒单'
      return S || '未知'
    },

    fetchInfo() {
      this.$axios.get(`/businesses/${this.id}`, {
        headers: { Authorization: `Bearer ${this.token}` }
      })
        .then(res => {
          const data = res?.data?.data ?? res?.data ?? {}
          this.info = data || {}
          const code = (data?.businessStatus || '').toString().toLowerCase()
          this.openStatus = (code === 'opening' ? 'opening' : 'closing')
        })
        .catch(err => {
          console.error('获取店铺信息失败', err)
          this.$message.error('获取店铺信息失败')
        })
    },

    saveOpenStatus() {
      if (!this.id) return
      const statusToSet = this.openStatus === 'opening' ? 'opening' : 'closing'
      this.saving = true

      this.$axios.put(`/businesses/${this.id}/status/${statusToSet}`, null, {
        headers: { Authorization: `Bearer ${this.token}` }
      })
        .then(() => {
          this.$message.success('营业状态已更新')
          this.fetchInfo()
        })
        .catch(err => {
          console.error('保存失败', err)
          this.$message.error('保存失败，请稍后重试')
        })
        .finally(() => { this.saving = false })
    },

    fetchOrders() {
      if (!this.id) return
      this.loadingOrders = true

      this.$axios.get(`/orders/${this.id}/business`, {
        headers: { Authorization: `Bearer ${this.token}` }
      })
        .then(res => {
          const arr = res.data.data
          const rawList = Array.isArray(arr) ? arr : []

          const mapped = rawList.map(o => {
            const rawState = o.status.toString().toUpperCase()
            const KNOWN = ['UNPAID', 'PAID', 'RECEIVED', 'ENDED', 'REFUNDED', 'REJECTED']
            const S = KNOWN.includes(rawState) ? rawState : 'PAID'

            const amount = (o?.orderTotal ?? o?.amount ?? 0)
            const count = (o?.itemCount ?? o?.item_count ?? 1)
            return {
              id: o?.id,
              status: S,
              summary: o?.summary || o?.remark || `${count} 件 · ¥${Number(amount).toFixed(2)}`
            }
          })

          this.orders = mapped.filter(x => x.status !== 'UNPAID')
        })
        .catch(err => {
          console.error('获取订单失败', err)
          this.orders = []
          this.$message.error('获取订单失败')
        })
        .finally(() => { this.loadingOrders = false })
    },

    updateOrder(o, target) {
      if (!o?.id) return
      const cur = (o.status || '').toUpperCase()
      const tar = (target || '').toLowerCase()

      const allow =
        (cur === 'PAID' && (tar === 'received' || tar === 'rejected')) ||
        (cur === 'RECEIVED' && tar === 'ended')

      if (!allow) return this.$message.warning('当前状态不可执行该操作')

      this.$axios.put(`/orders/${o.id}/${tar}`, null, {
        headers: { Authorization: `Bearer ${this.token}` }
      })
        .then(() => {
          const msg = tar === 'received' ? '已接单'
            : tar === 'rejected' ? '已拒单'
              : '已完成'
          this.$message.success(msg)
          this.fetchOrders()
        })
        .catch(err => {
          console.error('更新订单失败', err)
          this.$message.error('操作失败，请稍后再试')
        })
    }
  }
}
</script>

<style scoped>
.business-manage-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f9fa 0%, #e8f4f8 100%);
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
  padding-bottom: 16vw;
}

/* 顶部导航栏 */
.manage-header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 12vw;
  background: linear-gradient(135deg, #0097FF 0%, #0066cc 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 4vw;
  z-index: 1000;
  box-shadow: 0 4px 20px rgba(0, 151, 255, 0.3);
}

.back-btn,
.settings-btn {
  font-size: 5vw;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 2vw;
  border-radius: 50%;
}

.back-btn:hover,
.settings-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: scale(1.1);
}

.manage-header h1 {
  font-size: 4.5vw;
  font-weight: 600;
  margin: 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 主要内容区域 */
.manage-main {
  padding: 16vw 4vw 4vw;
  display: flex;
  flex-direction: column;
  gap: 4vw;
}

/* 卡片通用样式 */
.info-card,
.status-card,
.orders-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
}

.info-card:hover,
.status-card:hover,
.orders-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  align-items: center;
  padding: 4vw;
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f4ff 100%);
  border-bottom: 1px solid #f0f0f0;
}

.card-icon {
  width: 6vw;
  height: 6vw;
  background: linear-gradient(135deg, #0097FF 0%, #0066cc 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 3vw;
  margin-right: 3vw;
}

.card-header h2 {
  font-size: 4.2vw;
  font-weight: 600;
  color: #333;
  margin: 0;
  flex: 1;
}

/* 店铺信息卡片 */
.info-card .card-content {
  padding: 4vw;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 3vw 0;
  border-bottom: 1px solid #f5f5f5;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item i {
  width: 6vw;
  text-align: center;
  color: #0097FF;
  font-size: 4vw;
  margin-right: 3vw;
}

.info-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.info-label {
  font-size: 3.4vw;
  color: #666;
  margin-bottom: 1vw;
}

.info-value {
  font-size: 3.8vw;
  color: #333;
  font-weight: 500;
}

.info-value.highlight {
  color: #FF6B6B;
  font-weight: 600;
  font-size: 4.2vw;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 4vw;
  margin-top: 2vw;
}

/* 营业状态卡片 */
.status-content {
  padding: 4vw;
}

.status-toggle {
  display: flex;
  gap: 3vw;
  margin-bottom: 4vw;
}

.toggle-option {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 4vw 2vw;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  background: white;
}

.toggle-option.active {
  border-color: #0097FF;
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 151, 255, 0.3);
}

.toggle-option i:first-child {
  font-size: 6vw;
  color: #666;
  margin-bottom: 2vw;
}

.toggle-option.active i:first-child {
  color: #0097FF;
}

.toggle-option span {
  font-size: 3.8vw;
  font-weight: 500;
  color: #666;
}

.toggle-option.active span {
  color: #0097FF;
  font-weight: 600;
}

.status-indicator {
  position: absolute;
  top: -1vw;
  right: -1vw;
  width: 6vw;
  height: 6vw;
  background: #4CAF50;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 3vw;
}

.save-btn {
  width: 100%;
  padding: 3.5vw;
  background: linear-gradient(135deg, #0097FF 0%, #0066cc 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 4vw;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 2vw;
  box-shadow: 0 4px 12px rgba(0, 151, 255, 0.4);
}

.save-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 151, 255, 0.6);
}

.save-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

/* 订单卡片 */
.orders-count {
  font-size: 3.4vw;
  color: #666;
  background: #f0f0f0;
  padding: 1vw 2vw;
  border-radius: 10px;
}

/* 加载状态 */
.loading-state {
  padding: 8vw 4vw;
  text-align: center;
  color: #666;
}

.loading-spinner {
  margin-bottom: 3vw;
}

.loading-spinner i {
  font-size: 8vw;
  color: #0097FF;
  animation: spin 1s linear infinite;
}

.loading-state p {
  font-size: 3.8vw;
  margin: 0;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

/* 空状态 */
.empty-state {
  padding: 8vw 4vw;
  text-align: center;
  color: #999;
}

.empty-icon {
  width: 16vw;
  height: 16vw;
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 3vw;
}

.empty-icon i {
  font-size: 6vw;
  color: #2196F3;
}

.empty-state p {
  font-size: 4vw;
  margin: 0 0 1vw;
  font-weight: 500;
}

.empty-tip {
  font-size: 3.4vw;
  color: #bbb;
}

/* 订单列表 */
.orders-list {
  padding: 0 4vw 4vw;
}

.order-item {
  background: #fafafa;
  border-radius: 12px;
  padding: 4vw;
  margin-bottom: 3vw;
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

.order-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 3vw;
}

.order-id {
  display: flex;
  align-items: center;
  gap: 1.5vw;
  font-size: 3.6vw;
  color: #666;
}

.order-id i {
  color: #0097FF;
}

.order-status {
  padding: 1.5vw 3vw;
  border-radius: 20px;
  font-size: 3.2vw;
  font-weight: 500;
}

.status-paid {
  background: #FFF3E0;
  color: #FF9800;
}

.status-received {
  background: #E8F5E8;
  color: #4CAF50;
}

.status-ended {
  background: #E3F2FD;
  color: #2196F3;
}

.status-rejected {
  background: #FFEBEE;
  color: #F44336;
}

.order-content {
  margin-bottom: 3vw;
}

.order-summary {
  display: flex;
  align-items: center;
  gap: 2vw;
  font-size: 3.8vw;
  color: #333;
}

.order-summary i {
  color: #0097FF;
  font-size: 4vw;
}

.order-actions {
  display: flex;
  gap: 2vw;
  justify-content: flex-end;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 1.5vw;
  padding: 2.5vw 4vw;
  border: none;
  border-radius: 20px;
  font-size: 3.6vw;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 20vw;
  justify-content: center;
}

.accept-btn {
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}

.accept-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.5);
}

.reject-btn {
  background: linear-gradient(135deg, #F44336 0%, #da190b 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(244, 67, 54, 0.3);
}

.reject-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(244, 67, 54, 0.5);
}

.complete-btn {
  background: linear-gradient(135deg, #2196F3 0%, #0b7dda 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(33, 150, 243, 0.3);
}

.complete-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.5);
}

/* 底部导航 */
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 16vw;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-top: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  z-index: 100;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
  font-size: 3vw;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 2vw;
  border-radius: 10px;
}

.nav-item.active {
  color: #0097FF;
  transform: translateY(-3px);
}

.nav-item i {
  font-size: 5.5vw;
  margin-bottom: 1vw;
  transition: all 0.3s ease;
}

.nav-item.active i {
  transform: scale(1.2);
}

.nav-item span {
  font-size: 3vw;
  font-weight: 500;
}

/* 响应式设计 */
@media (min-width: 768px) {
  .business-manage-container {
    max-width: 500px;
    margin: 0 auto;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  }

  .manage-header {
    height: 60px;
    padding: 0 20px;
  }

  .manage-header h1 {
    font-size: 20px;
  }

  .back-btn,
  .settings-btn {
    font-size: 20px;
  }

  /* 其他桌面端样式调整... */
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.info-card,
.status-card,
.orders-card {
  animation: fadeInUp 0.5s ease-out;
}
</style>